<template>

  <div class="system-user-container">
    <el-card shadow="hover">
      <div class="system-menu-search mb15">
        <el-input v-model="search" size="default" placeholder="请输入姓名" style="max-width: 180px"></el-input>
      </div>
      <el-table :data="filterTableData" stripe style="width: 100%">
        <el-table-column type="index" :index="totalIndex" width="50px"/>
        <el-table-column prop="id" label="学号"></el-table-column>
        <el-table-column prop="name" label="姓名" min-width="80px" :fixed="themeConfig.isPhone" show-overflow-tooltip>
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <el-avatar style="width: 40px; height: 40px" :src="scope.row.avatar" fit="cover"/>
              <span style="margin-left: 10px">{{ scope.row.user.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="major.name" label="专业" width="100px" show-overflow-tooltip></el-table-column>
        <el-table-column prop="phone" label="联系方式" width="120px"></el-table-column>
        <el-table-column prop="user.email" label="邮箱" width="200px" show-overflow-tooltip></el-table-column>

        <!-- 添加权限级别列 -->
        <el-table-column prop="permission" label="权限级别" width="120px" align="center">
          <template #default="scope">
            <el-tag :type="getPermissionTagType(scope.row.permission)">{{ getPermissionText(scope.row.permission) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="加入时间" sortable show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" >
          <template #default="scope">
            <el-button size="small" type="warning" @click="onOpenPermissionDialog(scope.row)">修改权限</el-button>
            <el-button size="small" type="danger" @click="onRowDel(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          size="small"
          @size-change="onHandleSizeChange"
          @current-change="onHandleCurrentChange"
          class="mt15"
          :pager-count="5"
          :page-sizes="[10, 20, 30]"
          v-model:current-page="state.tableData.param.pageNum"
          background
          v-model:page-size="state.tableData.param.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 权限修改对话框 -->
    <el-dialog title="修改用户权限" v-model="permissionDialog.isShow" width="500px">
      <div v-if="permissionDialog.currentUser" class="permission-user-info">
        <p>正在为用户 <el-tag type="primary">{{ permissionDialog.currentUser.name }}</el-tag> 修改权限</p>
      </div>
      <el-divider></el-divider>
      <el-form :model="permissionForm" label-width="100px">
        <el-form-item label="权限级别:">
          <el-select v-model="permissionForm.permission" placeholder="请选择权限级别" style="width: 100%">
            <el-option label="指导教师" value="admin" />
            <el-option label="团队成员" value="manager" />
            <el-option label="游客" value="guest" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialog.isShow = false" size="default">取 消</el-button>
          <el-button type="primary" @click="savePermission" size="default">保 存</el-button>
        </span>
      </template>
    </el-dialog>

    <Dialog ref="DialogRef" @refresh="initTableData()"/>
  </div>
</template>

<script setup lang="ts">
import {reactive, onMounted, ref, computed} from "vue";
import {ElMessageBox, ElMessage} from "element-plus";
import {useThemeConfig} from "/@/stores/themeConfig";
import {storeToRefs} from "pinia";
import {deleteUser, getUserInfo, getUsers, resetPassword, updateUser} from "/@/views/user/users";
import {defineAsyncComponent} from "vue";

// 引入组件
const Dialog = defineAsyncComponent(() => import("/@/views/user/dialog.vue"));
const DialogRef = ref();

const storesThemeConfig = useThemeConfig();
const {themeConfig} = storeToRefs(storesThemeConfig);
const editableTabsValue = ref("0");

const state = reactive({
  keywords: "",
  tableData: {
    allData: [],
    total: 0,
    loading: false,
    param: {
      pageNum: 1,
      pageSize: 10
    }
  },
  editData: {}
});

// 权限对话框状态
const permissionDialog = reactive({
  isShow: false,
  currentUser: null
});

// 权限表单
const permissionForm = reactive({
  status: true,
  permission: 'user',
  permissionDesc: ''
});

const loading = ref(true);
const search = ref("");

const filterTableData = computed(() => {
  return state.tableData.allData
      .filter((data) => !search.value || data.name.toLowerCase().includes(search.value.toLowerCase()))
      .slice((state.tableData.param.pageNum - 1) * state.tableData.param.pageSize, state.tableData.param.pageNum * state.tableData.param.pageSize);
});

const totalIndex = computed(() => (state.tableData.param.pageNum - 1) * state.tableData.param.pageSize + 1);

const total = computed(() =>
    !search.value
        ? state.tableData.total
        : state.tableData.allData.filter((data) => !search.value || data.name.toLowerCase().includes(search.value.toLowerCase())).length
);

// 获取权限标签类型
const getPermissionTagType = (permission: string) => {
  switch (permission) {
    case 'admin': return 'danger';
    case 'user': return 'primary';
    case 'guest': return 'info';
    default: return 'info';
  }
};

// 获取权限文本
const getPermissionText = (permission: string) => {
  switch (permission) {
    case 'admin': return '指导教师';
    case 'user': return '团队成员';
    case 'guest': return '游客';
    default: return '普通用户';
  }
};

// 打开权限修改对话框
const onOpenPermissionDialog = (row: any) => {
  permissionDialog.currentUser = row;
  permissionForm.status = row.status !== undefined ? row.status : true;
  permissionForm.permission = row.permission || 'user';
  permissionForm.permissionDesc = row.permissionDesc || '';
  permissionDialog.isShow = true;
};

// 保存权限修改
const savePermission = async () => {
  if (!permissionDialog.currentUser) return;

  const userData = {
    ...permissionDialog.currentUser.data,
    status: permissionForm.status,
    permission: permissionForm.permission,
    permissionDesc: permissionForm.permissionDesc
  };

  try {
    // 调用更新用户API
    const res = await updateUser(userData);
    if (res.success) {
      ElMessage.success('权限修改成功');
      // 更新本地数据
      const userIndex = state.tableData.allData.findIndex(item => item.id === permissionDialog.currentUser.id);
      if (userIndex !== -1) {
        state.tableData.allData[userIndex].status = permissionForm.status;
        state.tableData.allData[userIndex].permission = permissionForm.permission;
        state.tableData.allData[userIndex].permissionDesc = permissionForm.permissionDesc;
      }
      permissionDialog.isShow = false;
    } else {
      ElMessage.error('权限修改失败');
    }
  } catch (error) {
    ElMessage.error('权限修改失败');

    console.error('Permission update error:', error);
  }
};

// 初始化表格数据
const initTableData = async () => {
  state.tableData.loading = true;

  getUserInfo({
    page: state.tableData.param.pageNum,
    pageSize: state.tableData.param.pageSize,
    keywords: state.keywords,
  }).then((res) => {
    state.tableData.allData = res.data.allUser;
    state.tableData.total = res.data.total;
    state.tableData.loading = false;
  })
      .catch(() => {
        state.tableData.loading = false;
      });
};

// 删除用户
const onRowDel = (row: any) => {
  ElMessageBox.confirm(`此操作将永久删除账户名称："${row.name}"，是否继续?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
      .then(async () => {
        await deleteUser(row.id).then((res) => {
          res.success && ElMessage.success("删除成功");
        });
        initTableData();
      })
};

// 分页改变
const onHandleSizeChange = (val: number) => {
  state.tableData.param.pageSize = val;
};

// 分页改变
const onHandleCurrentChange = (val: number) => {
  state.tableData.param.pageNum = val;
};

// 页面加载时
onMounted(() => {
  initTableData();
});

const onOpenAddDialog = () => {
  DialogRef.value.openDialog();
};
</script>
